package controllers;

import helpers.DateHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.MetaSeoModel;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

import services.GetInfoDomain;
import systems.ConfigSystem;
import systems.CurrentProcess;
import systems.RecentlyDomain;
import systems.RecentlyUpdate;

import models.DirectoryModel;
import models.GoogleAdsenceModel;
import models.GoogleAnalyticModel;
import models.InLinkModel;
import models.IpAddressModel;
import models.DomainModel;

import entities.Domain;
import entities.GoogleAdsense;
import entities.GoogleAnalytic;
import entities.InLink;
import entities.IpAddress;
import entities.MetaSeo;
import entities.SiteConfig;
import entities.User;

public class DomainInfoServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		//Set message error
		if (name == null || name.isEmpty() || !UrlHelper.checkDomain(name)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (!name.equalsIgnoreCase(UrlHelper.getMainDomain(name))) {
			response.sendRedirect("/info/" + UrlHelper.getMainDomain(name));
			return ;
		}
		
		//Check domain is canada with extension .ca
		String extension = siteConfig.getExtensionDetect().replaceFirst(".", "").replace(" .", " ");
		if (!siteConfig.getExtensionDetect().isEmpty() && !UrlHelper.checkSpecialDomain(name, extension)) {
			//Cache header
			response.addHeader("Cache-Control", "public, max-age=60000");
			
			String titleMsg = name + " Page not found";
			String msg = "Domain " + name + " isn't the domain extension with " + extension;
			printError(titleMsg, msg, request, response);
			return;
		}
		
		
		DomainModel domainModel = DomainModel.getInstance();
		Domain domain = domainModel.get(name);
		
		if (domain == null) {
			
			//Get data
			domain = new Domain();
			domain.setProcessing(true);
			domain.setDomain(name);
			
			
			GetInfoDomain getInfoDomain = new GetInfoDomain(domain);
			getInfoDomain.getSiteInfo();
			
			domain = getInfoDomain.getDomain();
			TreeMap check = getInfoDomain.getCheck();
			
			if (check != null && check.get("domain") != null) {
				//Cache header
				response.addHeader("Cache-Control", "public, max-age=60000");
				
				String titleMsg = name + " Page not found";
				String msg = (String) check.get("domain");
				msg += "<br /> Please check more information about " + name + " in <a href=\"http://site-value.us/analysis/"+name+"\">site-value.us</a>";
				printError(titleMsg, msg, request, response);
				return;
			}
			
			if (!domain.isExists()) {
				String titleMsg = name + " Page not found"; 
				String msg = "This domain " + name + " doesn't exists.";
				printError(titleMsg, msg, request, response);
				return;
			}
			
			domainModel.insert(domain);
			
			//Get more info
			if (domain.isExists()) {
				getInfoDomain.getStep1();
				
				domain.setProcessing(false);
				domainModel.insert(domain);
				
				//Update googleAnalytic model
				if (!domain.getGoogleAnalyticId().isEmpty()) {
					GoogleAnalyticModel googleAnalyticModel = GoogleAnalyticModel.getInstance();
					googleAnalyticModel.insert(domain.getGoogleAnalyticId(), domain.getDomain());
				}
				
				//Update googleAdsense model
				if (!domain.getGoogleAdsenseId().isEmpty()) {
					GoogleAdsenceModel googleAdsenseModel = GoogleAdsenceModel.getInstance();
					googleAdsenseModel.insert(domain.getGoogleAdsenseId(), domain.getDomain());
				}
				
				//Update IpAddress Model
				if (!domain.getIpAddress().isEmpty()) {
					IpAddressModel ipAddressModel = IpAddressModel.getInstance();
					ipAddressModel.insert(domain.getIpAddress(), domain.getDomain());
				}
				
				//Update inlink
				/*if (domain.getOutlink().size() > 0) {
					InLinkModel inlinkModel = InLinkModel.getInstance();
					inlinkModel.insert(domain.getDomain(), domain.getOutlink());
				}*/
				
				CurrentProcess.remove(name);
				RecentlyUpdate.insert(name);
				
				//Update directory
				DirectoryModel directoryModel = DirectoryModel.getInstance();
				directoryModel.insert(domain.getDomain());
			}
			
		}
		
		if (!domain.isExists()) {
			String titleMsg = name + " Page not found"; 
			String msg = "This domain " + name + " doesn't exists.";
			printError(titleMsg, msg, request, response);
			return;
		}
		
		if (domain.getStatus() == -1) {
			String titleMsg = name + " Page not found"; 
			String msg = "This domain " + name + " doesn't exists.";
			printError(titleMsg, msg, request, response);
			return;
		}
		
		//Get google analytic
		GoogleAnalyticModel googleAnalyticData = GoogleAnalyticModel.getInstance();
		GoogleAnalytic googleAnalytic = googleAnalyticData.get(domain.getGoogleAnalyticId());
		
		//Get google adsence
		GoogleAdsenceModel googleAdsenceData = GoogleAdsenceModel.getInstance();
		GoogleAdsense googleAdsense = googleAdsenceData.get(domain.getGoogleAdsenseId());
		
		//Get inlink
		InLinkModel oData = InLinkModel.getInstance();
		InLink inlink = oData.get(domain.getDomain());
		
		//Get same domain ip address
		IpAddressModel ipAddressModel = IpAddressModel.getInstance();
		IpAddress ipAddress = null;
		if (!domain.getIpAddress().isEmpty()) {
			ipAddress = ipAddressModel.get(domain.getIpAddress());
		}
		
		//Set into recentSiteUpdate
		RecentlyDomain.insert(name);
		
		//Set seo content
        MetaSeoModel metaseoModel = MetaSeoModel.getInstance();
        MetaSeo metaseo = metaseoModel.get("info");
		
		//Cache header
		response.addHeader("Cache-Control", "public, max-age=60000");
		
		request.setAttribute("domain", domain);
		request.setAttribute("googleAnalytic", googleAnalytic);
		request.setAttribute("googleAdsense", googleAdsense);
		request.setAttribute("inlink", inlink);
		request.setAttribute("ipAddress", ipAddress);
		request.setAttribute("metaseo", metaseo);
		try {
			request.getRequestDispatcher("/pages/info.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
	private void printError(String title, String msg, 
			HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		request.setAttribute("title", title);
		request.setAttribute("msg", msg);
		try {
			request.getRequestDispatcher("/pages/message.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
	private String getLanguage(String lang) {
		TreeMap<String, String> languages = new TreeMap<String, String>();
		languages.put("en", "English");
		languages.put("vi", "Vietnamese");
		String language = languages.get(lang);
		
		return language;
	}
}
